route.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import NextAuth from "next-auth";
  2. import CredentialsProvider from "next-auth/providers/credentials";
  3. import * as R from "ramda";
  4. export const authOptions = {
  5. // Configure one or more authentication providers
  6. providers: [
  7. CredentialsProvider({
  8. // The name to display on the sign in form (e.g. 'Sign in with...')
  9. name: "Cocorobo cloud",
  10. // The credentials is used to generate a suitable form on the sign in page.
  11. // You can specify whatever fields you are expecting to be submitted.
  12. // e.g. domain, username, password, 2FA token, etc.
  13. // You can pass any HTML attribute to the <input> tag through the object.
  14. credentials: {
  15. loginUsername: { label: "用户名", type: "text" },
  16. loginPassword: { label: "密码", type: "password" },
  17. },
  18. async authorize(credentials, req) {
  19. // You need to provide your own logic here that takes the credentials
  20. // submitted and returns either a object representing a user or value
  21. // that is false/null if the credentials are invalid.
  22. // e.g. return { id: 1, name: 'J Smith', email: 'jsmith@example.com' }
  23. // You can also use the `req` object to obtain additional parameters
  24. // (i.e., the request IP address)
  25. const res = await fetch("https://beta.api.cocorobo.cn/api/user", {
  26. method: "POST",
  27. body: JSON.stringify(
  28. R.pick(["loginUsername", "loginPassword"], credentials)
  29. ),
  30. headers: {
  31. "Content-Type": "application/json",
  32. Origin: "https://edu.cocorobo.cn",
  33. },
  34. });
  35. if (res.status !== 200) {
  36. return null;
  37. }
  38. const resJson = await res.json();
  39. const user = resJson?.[0]?.[0];
  40. // If no error and we have user data, return it
  41. if (res.ok && user && user.active) {
  42. return { ...user, id: user.userid, name: user.username };
  43. }
  44. // Return null if user data could not be retrieved
  45. return null;
  46. },
  47. }),
  48. ],
  49. callbacks: {
  50. async session({ session, token }) {
  51. console.log(session, token);
  52. // Send properties to the client, like an access_token from a provider.
  53. session.user.id = token.sub;
  54. try {
  55. const res = await fetch(
  56. `https://pbl.cocorobo.cn/api/pbl/selectUser?userid=${token.sub}`,
  57. {
  58. method: "GET",
  59. headers: {
  60. "Content-Type": "application/json",
  61. },
  62. }
  63. );
  64. const username = (await res.json())?.[0]?.[0]?.username;
  65. session.user.name = username;
  66. } catch (e) {
  67. session.user.name = token.name;
  68. }
  69. return session;
  70. },
  71. },
  72. };
  73. const handler = NextAuth(authOptions);
  74. export { handler as GET, handler as POST };